package uk.ac.lkl.takteen.energyapp;

import java.io.FileNotFoundException;
import java.io.IOException;

import uk.ac.lkl.takteen.energyapp.data.EnergyAppDatabaseMetadata;
import uk.ac.lkl.takteen.energyapp.data.EnergyAppProvider;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class ChallengeEditor extends Activity {

	private Cursor cursor;
	private Uri mUri;

	private int pauseIntent;
	private static final int DELETING = 1;

	private EditText mChallengeName;
	private Spinner mChallengeTypeSpinner;
	private String challengeType;
	private int challengeTypePos;
	private Spinner mEnergyTypeSpinner;
	private String energyType;
	private int energyTypePos;
	private ImageView mChallengeImage;
	private EditText mChallengeInfo;
	private EditText mChallengeLink;

	private static final int COLUMN_INDEX_NAME = 1;
	private static final int COLUMN_INDEX_CREATED_BY = 2;
	private static final int COLUMN_INDEX_LAST_MODIFIED_BY = 3;
	private static final int COLUMN_INDEX_CHALLENGE_TYPE = 4;
	private static final int COLUMN_INDEX_CHALLENGE_TYPE_POS = 5;
	private static final int COLUMN_INDEX_ENERGY_TYPE = 6;
	private static final int COLUMN_INDEX_ENERGY_TYPE_POS = 7;
	private static final int COLUMN_INDEX_IMAGE = 8;
	private static final int COLUMN_INDEX_INFO = 9;
	private static final int COLUMN_INDEX_LINK = 10;

	// codes for picking/taking image
	private static final int PICK_IMAGE = 1;
	private static final int TAKE_PHOTO = 2;

	// codes for creating dialogs
	private static final int DIALOG_SAVE = 1;
	private static final int DIALOG_PHOTO = 2;

	private Uri new_photo; // used to store photos taken
	private String item_imageuri = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.challenge_editor);

		mChallengeTypeSpinner = (Spinner) findViewById(R.id.challenge_type_spinner);
		ArrayAdapter<CharSequence> adapterChallenge = ArrayAdapter
				.createFromResource(this, R.array.challenge_type_array,
						android.R.layout.simple_spinner_item);
		adapterChallenge
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mChallengeTypeSpinner.setAdapter(adapterChallenge);
		mChallengeTypeSpinner
				.setOnItemSelectedListener(new MyOnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						challengeType = parent.getItemAtPosition(pos)
								.toString();
						challengeTypePos = pos;
					}

					public void onNothingSelected(AdapterView parent) {
						// Do nothing.
					}
				});

		mEnergyTypeSpinner = (Spinner) findViewById(R.id.energy_type_spinner);
		ArrayAdapter<CharSequence> adapterEnergy = ArrayAdapter
				.createFromResource(this, R.array.energy_type_array,
						android.R.layout.simple_spinner_item);
		adapterEnergy
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mEnergyTypeSpinner.setAdapter(adapterEnergy);
		mEnergyTypeSpinner
				.setOnItemSelectedListener(new MyOnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						energyType = parent.getItemAtPosition(pos).toString();
						energyTypePos = pos;
					}

					public void onNothingSelected(AdapterView parent) {
						// Do nothing.
					}
				});

		mChallengeName = (EditText) findViewById(R.id.challenge_name);
		mChallengeTypeSpinner = (Spinner) findViewById(R.id.challenge_type_spinner);
		mEnergyTypeSpinner = (Spinner) findViewById(R.id.energy_type_spinner);
		mChallengeImage = (ImageView) findViewById(R.id.challenge_image);
		mChallengeInfo = (EditText) findViewById(R.id.challenge_information);
		mChallengeLink = (EditText) findViewById(R.id.challenge_link);

		final Intent intent = getIntent();
		final String action = intent.getAction();
		mUri = intent.getData();

		if (Intent.ACTION_INSERT.equals(action)) {
			// ContentValues values = new ContentValues();
			// values.put(EnergyAppDatabaseMetadata.CREATED_BY, "temp");
			// mUri = getContentResolver().insert(getIntent().getData(),
			// values);
		}

		if (Intent.ACTION_EDIT.equals(action)) {
			// get name of the pledge based on uri
			cursor = managedQuery(mUri,
					EnergyAppDatabaseMetadata.PROJECTION_USER_CHALLENGES, null,
					null, null);
			cursor.moveToFirst();

			mChallengeName.setText(cursor.getString(COLUMN_INDEX_NAME));
			mChallengeName.setInputType(InputType.TYPE_NULL);
			mChallengeTypeSpinner.setSelection(
					cursor.getInt(COLUMN_INDEX_CHALLENGE_TYPE_POS), false);
			mEnergyTypeSpinner.setSelection(
					cursor.getInt(COLUMN_INDEX_ENERGY_TYPE_POS), false);
			showPhoto();
			mChallengeInfo.setText(cursor.getString(COLUMN_INDEX_INFO));
			mChallengeLink.setText(cursor.getString(COLUMN_INDEX_LINK));
		}

		final Button sendChallengeButton = (Button) findViewById(R.id.send_challenge_button);
		sendChallengeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// to do only if there is an image
				createChallenge();
				if (!TextUtils.isEmpty(item_imageuri)) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(item_imageuri), ChallengeEditor.this,
							ChallengeImage.class);
					intent.putExtra(EnergyAppDatabaseMetadata.CHALLENGE_NAME,
							mChallengeName.getText().toString());
					intent.putExtra(EnergyAppDatabaseMetadata.CHALLENGE_LINK,
							mChallengeLink.getText().toString());
					intent.putExtra(EnergyAppDatabaseMetadata.CHALLENGE_TYPE,
							challengeType);
					intent.putExtra(EnergyAppDatabaseMetadata.ENERGY_TYPE,
							energyType);
					intent.putExtra(EnergyAppDatabaseMetadata.CHALLENGE_INFO,
							mChallengeInfo.getText().toString());
					startActivity(intent);
				} else {
					Toast.makeText(ChallengeEditor.this,
							"Add an image before sending your challenge",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		final Button deleteChallengeButton = (Button) findViewById(R.id.delete_challenge_button);
		deleteChallengeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				pauseIntent = DELETING;
				cursor = null;
				showDialog(DIALOG_SAVE);

				// String whenSelectionStatement = EnergyAppDatabaseMetadata._ID
				// + "=" + mUri.getLastPathSegment();
				// getContentResolver().delete(
				// EnergyAppProvider.USER_CHALLENGES_DIR,
				// whenSelectionStatement, null);
				// Intent intent = new Intent(Intent.ACTION_VIEW,
				// EnergyAppProvider.USER_CHALLENGES_DIR,
				// ChallengeEditor.this, UserChallengesList.class);
				// startActivity(intent);
			}
		});

		Button addPhotoButton = (Button) findViewById(R.id.add_challenge_photo_button);
		addPhotoButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DIALOG_PHOTO);
			}
		});
	}

	@Override
	public void onBackPressed() {
		Log.d("CDA", "onBackPressed Called");
		final Intent intent = getIntent();
		final String action = intent.getAction();
		if (Intent.ACTION_INSERT.equals(action)) {
			String name = mChallengeName.getText().toString();
			String challengeInfo = mChallengeInfo.getText().toString();
			String challengeLink = mChallengeLink.getText().toString();
			if (name.length() != 0 || challengeInfo.length() != 0
					|| challengeLink.length() != 0)
				showDialog(DIALOG_SAVE);
			else {
				Intent newIntent = new Intent(Intent.ACTION_VIEW, null,
						ChallengeEditor.this, EnergyAppActivity.class);
				startActivity(newIntent);
			}
		} else {
			createChallenge();
			Intent newIntent = new Intent(Intent.ACTION_VIEW,
					EnergyAppProvider.USER_CHALLENGES_DIR,
					ChallengeEditor.this, Challenges.class);
			startActivity(newIntent);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (cursor != null) {
			// Requery in case something changed while paused (such as the
			// title)
			cursor.requery();

			// Make sure we are at the one and only row in the cursor.
			cursor.moveToFirst();

			showPhoto();
			// If something went wrong tell the user...
		} else {
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		// The user is going somewhere else, so make sure their current
		// changes are safely saved away in the provider.

		if (cursor != null && pauseIntent != DELETING) {
			// if this is a new note and it has no title or notes or image or
			// media assume do not want to save
			// and delete it - possibly a bad assumption.
			// int length = mItemName.getText().toString().length() +
			// mText.getText().toString().length() + item_imageuri.length() +
			// item_sounduri.length();
			// if (isFinishing() && (length == 0) && !mNoteOnly && (mState ==
			// STATE_INSERT)) {
			// setResult(RESULT_CANCELED);
			// deleteNote();
			// } else {
			// updateProvider();
			// }
			createChallenge();
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		System.gc();

	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (requestCode) {
		case PICK_IMAGE:
			if (resultCode == RESULT_OK) {
				try {
					item_imageuri = intent.getDataString();
					Toast.makeText(this, "photo added", Toast.LENGTH_SHORT)
							.show();
					//createChallenge();
				} catch (Exception e) {
					Toast.makeText(this, "Error adding image - not saved",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(this, "Image add not completed " + resultCode,
						Toast.LENGTH_SHORT).show();
			}
			break;
		case TAKE_PHOTO:
			if (resultCode == RESULT_OK) {
				try {
					item_imageuri = "content://media"
							+ new_photo.getEncodedPath();
					Log.w("image uri", item_imageuri.toString());
					Toast.makeText(this, "photo taken", Toast.LENGTH_SHORT)
							.show();
					//createChallenge();
					if (intent == null) {
						// updateProvider();
					} else {
						// removing this makes it work on HTC but... still
						// crashes if image size is too large
						// item_imageuri = intent.toURI();
						// Toast.makeText(this, "intent to uri is" +
						// item_imageuri, Toast.LENGTH_SHORT).show();

						// item_imageuri = photo_uri.getEncodedPath();
						// updateProvider();
					}
				} catch (Exception e) {
					if (new_photo != null)
						getContentResolver().delete(new_photo, null, null);
					Toast.makeText(this, "Error taking photo - not saved",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(this, "Take photo activity not completed",
						Toast.LENGTH_SHORT).show();
				getContentResolver().delete(new_photo, null, null);
			}
			break;
		}
	}

	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case DIALOG_SAVE:
			builder.setTitle("Save")
					.setMessage("Do you want to save this challenge?")
					.setPositiveButton("Save",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									createChallenge();
									dialog.cancel();
									if (Intent.ACTION_INSERT.equals(getIntent()
											.getAction())) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW, null,
												ChallengeEditor.this,
												EnergyAppActivity.class);
										startActivity(intent);
									} else if (Intent.ACTION_EDIT
											.equals(getIntent().getAction())) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW,
												EnergyAppProvider.USER_CHALLENGES_DIR,
												ChallengeEditor.this,
												Challenges.class);
										startActivity(intent);
									}
								}
							})
					.setNegativeButton("Delete",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									pauseIntent = DELETING;
									cursor = null;
									String whenSelectionStatement = EnergyAppDatabaseMetadata._ID
											+ "=" + mUri.getLastPathSegment();
									getContentResolver()
											.delete(EnergyAppProvider.USER_CHALLENGES_DIR,
													whenSelectionStatement,
													null);
									dialog.cancel();
									if (Intent.ACTION_INSERT.equals(getIntent()
											.getAction())) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW, null,
												ChallengeEditor.this,
												EnergyAppActivity.class);
										startActivity(intent);
									} else if (Intent.ACTION_EDIT
											.equals(getIntent().getAction())) {
										Intent intent = new Intent(
												Intent.ACTION_VIEW,
												EnergyAppProvider.USER_CHALLENGES_DIR,
												ChallengeEditor.this,
												Challenges.class);
										startActivity(intent);
									}
								}
							});
			break;
		case DIALOG_PHOTO:
			builder.setTitle("Take or pick a photo")
					.setMessage(
							"Do you want to take a photo or pick an existing one?")
					.setPositiveButton("Take photo with camera",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									Intent photoTakerIntent = new Intent(
											MediaStore.ACTION_IMAGE_CAPTURE);
									String photoName = mChallengeName.getText()
											.toString();
									ContentValues values = new ContentValues();
									values.put(MediaStore.Images.Media.TITLE,
											photoName);
									values.put(
											MediaStore.Images.Media.DESCRIPTION,
											"Image for " + photoName);
									new_photo = getContentResolver()
											.insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
													values);
									photoTakerIntent.putExtra(
											MediaStore.EXTRA_OUTPUT, new_photo);
									// delete if not taken e.g
									// getContentResolver().delete(note_photo,
									// null, null) in
									// actionReturn;
									try {
										// item_imageuri = "content://media" +
										// new_photo.getEncodedPath();
										startActivityForResult(
												photoTakerIntent, TAKE_PHOTO);
									} catch (android.content.ActivityNotFoundException ex) {
										Toast.makeText(
												ChallengeEditor.this,
												"No apps registered for this intent",
												Toast.LENGTH_SHORT).show();
										getContentResolver().delete(new_photo,
												null, null);
									}

								}
							})
					.setNegativeButton("Pick existing photo",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent imagePickerIntent = new Intent(
											Intent.ACTION_GET_CONTENT);
									imagePickerIntent.setType("image/*");
									imagePickerIntent
											.addCategory(Intent.CATEGORY_OPENABLE);
									try {
										startActivityForResult(Intent
												.createChooser(
														imagePickerIntent,
														"Pick image using"),
												PICK_IMAGE);
									} catch (android.content.ActivityNotFoundException ex) {
										Toast.makeText(
												ChallengeEditor.this,
												"No apps registered for this intent",
												Toast.LENGTH_SHORT).show();
									}
								}
							});
		default:

		}
		return builder.create();
	}

	public void showPhoto() {
		// If there is an image for this item we set the ImageView to
		// display it
		item_imageuri = cursor.getString(COLUMN_INDEX_IMAGE);
		if (!TextUtils.isEmpty(item_imageuri)) {
			Uri imageUri = Uri.parse(item_imageuri);
			// This approach works with HTC - stops crashes - but is too
			// slow!
			/*
			 * String path = imageUri.getPath(); BitmapFactory.Options
			 * options=new BitmapFactory.Options(); options.inSampleSize = 4;
			 * Bitmap preview = BitmapFactory.decodeFile(path, options);
			 */

			// THIS SECTION UNCOMMENT FOR HTC
			try {
				Bitmap full_size, preview = null;
				full_size = MediaStore.Images.Media.getBitmap(
						getContentResolver(), imageUri);
				int width = full_size.getWidth();
				int newWidth = 400;
				float scale_factor = (float) newWidth / width;
				int height = full_size.getHeight();
				int newHeight = Math.round(height * scale_factor);
				/*
				 * full_size.getWidth()/width; int height = (int)
				 * Math.ceil(full_size.getHeight()/scale_factor);
				 */
				preview = Bitmap.createScaledBitmap(full_size, newWidth,
						newHeight, false);
				full_size.recycle();
				mChallengeImage.setScaleType(ScaleType.CENTER);
				// mImageView.setMaxWidth(400);
				if (preview == null) {
					mChallengeImage.setImageURI(imageUri);
				} else {
					mChallengeImage.setImageBitmap(preview);
				}
				mChallengeImage.setVisibility(View.VISIBLE);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				mChallengeImage.setVisibility(View.GONE);
				e.printStackTrace();
			} catch (IOException e) {
				mChallengeImage.setVisibility(View.GONE);
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			// if the image uri string is empty make sure view is empty
			mChallengeImage.setVisibility(View.GONE);
		}
	}

	public void createChallenge() {

		String name = mChallengeName.getText().toString();
		if (name.length() == 0)
			name = "Nameless challenge";
		String challengeInfo = mChallengeInfo.getText().toString();
		String challengeLink = mChallengeLink.getText().toString();
		ContentValues values = new ContentValues();
		values.put(EnergyAppDatabaseMetadata.CHALLENGE_NAME, name);
		values.put(EnergyAppDatabaseMetadata.CHALLENGE_TYPE, challengeType);
		values.put(EnergyAppDatabaseMetadata.CHALLENGE_TYPE_POS,
				challengeTypePos);
		values.put(EnergyAppDatabaseMetadata.ENERGY_TYPE, energyType);
		values.put(EnergyAppDatabaseMetadata.ENERGY_TYPE_POS, energyTypePos);
		values.put(EnergyAppDatabaseMetadata.CHALLENGE_IMAGE, item_imageuri);
		values.put(EnergyAppDatabaseMetadata.CHALLENGE_INFO, challengeInfo);
		values.put(EnergyAppDatabaseMetadata.CHALLENGE_LINK, challengeLink);
		// add to database
		// if intent is view then update
		// if intent is insert then create a new one
		if (Intent.ACTION_INSERT.equals(getIntent().getAction())) {
			values.put(EnergyAppDatabaseMetadata.CREATED_BY, "temp");
			values.put(EnergyAppDatabaseMetadata.LAST_MODIFIED_BY, "temp");
			mUri = getContentResolver().insert(getIntent().getData(), values);
			// String whenSelectionStatement = EnergyAppDatabaseMetadata._ID +
			// "="
			// + mUri.getLastPathSegment();
			// getContentResolver().update(mUri, values, whenSelectionStatement,
			// null);
		} else if (Intent.ACTION_EDIT.equals(getIntent().getAction())) {
			String whenSelectionStatement = EnergyAppDatabaseMetadata._ID + "="
					+ mUri.getLastPathSegment();
			getContentResolver().update(getIntent().getData(), values,
					whenSelectionStatement, null);
		}
	}
}
